<template>
  <div class="dashboard-container">
    <el-container style="height: calc(100vh - 40px);"> <!-- 减去footer的高度 -->
      <el-aside width="250px" class="sidebar">
        <div class="logo">E特尔诺</div>
        <el-menu
          router true
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          unique-opened
          @select="handleMenuSelect"
        >
          <el-submenu index="1">
            <template slot="title">
              <i class="el-icon-menu"></i>
              <span>基础管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="apimanagement">API管理</el-menu-item>
              <el-menu-item index="apiAdd">新增API</el-menu-item>
              <el-menu-item index="logmanagement">日志管理</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-submenu index="2">
            <template slot="title">
              <i class="el-icon-setting"></i>
              <span>系统管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="usermanagement">用户管理</el-menu-item>
              <el-menu-item index="apireview">审核/上线</el-menu-item>
              <el-menu-item index="pendingreview">我的审核</el-menu-item>
              <el-menu-item index="problemfeedback">我的上报</el-menu-item>
              <el-menu-item index="mybug">我的缺陷</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-submenu index="3">
            <template slot="title">
              <i class="el-icon-document"></i>
              <span>模板管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="categorymanagement">种类管理</el-menu-item>
              <el-menu-item index="policymanagement">参数管理</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-submenu index="4">
            <template slot="title">
              <i class="el-icon-lock"></i>
              <span>安全中心</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="interfacealert">接口告警</el-menu-item>
              <el-menu-item index="informationsecurity">信息安全</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header class="header">
          <div class="header-left">E特尔诺管理平台</div>
          <div class="header-right">
            <span>当前用户: {{ currentUser }}</span>
            <span>当前时间: {{ currentTime }}</span>
            <el-button type="text" @click="openGitHub">GitHub主页</el-button>
            <el-button type="text" @click="feedbackDialogVisible = true" class="feedback-btn">
              <i class="el-icon-question"></i> 问题反馈
            </el-button>
          </div>
        </el-header>
        <el-main class="main-content">
          <el-tabs
            v-model="activeTab"
            type="card"
            @tab-remove="removeTab"
            @tab-click="handleTabClick"
          >
            <el-tab-pane
              v-for="tab in tabs"
              :key="tab.name"
              :label="tab.label"
              :name="tab.name"
              :closable="tab.name !== 'apimanagement'"
            >
            </el-tab-pane>
          </el-tabs>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
    <div class="footer">
      <p>&copy; 2023 Etnor. All rights reserved. | Supported by Lucas Studio</p>
    </div>

    <el-dialog title="问题反馈" :visible.sync="feedbackDialogVisible" width="50%" class="feedback-dialog">
      <el-form :model="feedbackForm" :rules="feedbackRules" ref="feedbackForm" label-width="120px">
        <el-form-item label="问题描述" prop="description">
          <el-input type="textarea" v-model="feedbackForm.description" placeholder="请输入问题描述，不少于10个字"></el-input>
        </el-form-item>
        <el-form-item label="紧急程度" prop="urgency">
          <el-select v-model="feedbackForm.urgency" placeholder="请选择紧急程度">
            <el-option label="低" value="low"></el-option>
            <el-option label="中" value="medium"></el-option>
            <el-option label="高" value="high"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指派系统管理员" prop="admin">
          <el-select v-model="feedbackForm.admin" placeholder="请选择系统管理员">
            <el-option v-for="admin in admins" :key="admin.id" :label="admin.name" :value="admin.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题类型" prop="type">
          <el-select v-model="feedbackForm.type" placeholder="请选择问题类型">
            <el-option v-for="type in issueTypes" :key="type.id" :label="type.name" :value="type.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属空间" prop="workspaceId">
          <el-select v-model="feedbackForm.workspaceId" placeholder="请选择所属空间">
            <el-option v-for="workspace in workspaces" :key="workspace.id" :label="workspace.name" :value="workspace.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="feedbackForm.note" placeholder="请输入备注（选填）"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="feedbackDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFeedback">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import router from '@/router';
import axios from 'axios';

export default {
  mounted() {
    document.title = 'E特尔诺-管理平台';
  },
  data() {
    return {
      currentUser: 'Admin',
      currentTime: new Date().toLocaleString(),
      activeMenu: 'apimanagement',  // 默认激活的菜单项
      activeTab: 'apimanagement',   // 默认激活的标签页
      tabs: [
        { label: 'API管理', name: 'apimanagement' }
      ],
      feedbackDialogVisible: false,
      feedbackForm: {
        description: '',
        urgency: '',
        admin: '',
        type: '',
        note: '',
        workspaceId: ''
      },
      feedbackRules: {
        description: [
          { required: true, message: '请输入问题描述', trigger: 'blur' },
          { min: 10, message: '问题描述不少于10个字', trigger: 'blur' }
        ],
        urgency: [
          { required: true, message: '请选择紧急程度', trigger: 'change' }
        ],
        admin: [
          { required: true, message: '请选择系统管理员', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择问题类型', trigger: 'change' }
        ],
        workspaceId: [
          { required: true, message: '请选择所属空间', trigger: 'change' }
        ]
      },
      admins: [],
      issueTypes: [],
      workspaces: []
    };
  },
  methods: {
    openGitHub() {
      window.open('https://github.com', '_blank');
    },
    handleMenuSelect(index) {
      const tab = this.tabs.find(t => t.name === index);
      if (!tab) {
        const route = this.$router.getRoutes().find(r => r.name === index);
        if (route) {
          this.tabs.push({ label: route.meta.title, name: index });
        }
      }
      this.activeTab = index;
      this.$router.push({ name: index });
    },
    handleTabClick(tab) {
      this.$router.push({ name: tab.name });
    },
    removeTab(targetName) {
      this.tabs = this.tabs.filter(tab => tab.name !== targetName);
      if (this.activeTab === targetName) {
        this.activeTab = this.tabs.length ? this.tabs[this.tabs.length - 1].name : '';
        this.$router.push({ name: this.activeTab });
      }
    },
    submitFeedback() {
      this.$refs.feedbackForm.validate((valid) => {
        if (valid) {
          // 准备数据
          const feedbackData = {
            description: this.feedbackForm.description,
            urgency: this.feedbackForm.urgency,
            adminId: this.feedbackForm.admin,
            issueType: this.feedbackForm.type,
            note: this.feedbackForm.note,
            req_id: this.feedbackForm.workspaceId
          };
          // 调用后端接口
          axios.post('/api/system/problemsubmit', feedbackData)
            .then(response => {
              if (response.data.code === 200) {
                this.$message({
                  message: '反馈提交成功',
                  type: 'success'
                });
                this.feedbackDialogVisible = false;
                this.resetFeedbackForm();
              } else {
                this.$message.error('反馈提交失败');
              }
            })
            .catch(error => {
              console.error('反馈提交失败', error);
              this.$message.error('反馈提交失败');
            });
        } else {
          this.$message.error('请填写完整信息');
          return false;
        }
      });
    },
    resetFeedbackForm() {
      this.feedbackForm.description = '';
      this.feedbackForm.urgency = '';
      this.feedbackForm.admin = '';
      this.feedbackForm.type = '';
      this.feedbackForm.note = '';
      this.feedbackForm.workspaceId = '';
    },
    fetchBaseParams() {
      axios.get('/api/system/baseParms')
        .then(response => {
          if (response.data.code === 200) {
            const data = response.data.data;
            this.admins = data.admins.map(admin => ({ id: admin.account, name: admin.username }));
            this.issueTypes = data.problemList.map(problem => ({ id: problem.id, name: problem.kind }));
          } else {
            this.$message.error('获取基础参数失败');
          }
        })
        .catch(error => {
          console.error('获取基础参数失败', error);
          this.$message.error('获取基础参数失败');
        });
    },
    fetchWorkspaceTree() {
      axios.get('/api/system/getTopSpace')
        .then(response => {
          if (response.data.code === 200) {
            const data = response.data.data;
            this.workspaces = data.map(workspace => ({
              id: workspace.id,
              name: workspace.name
            }));
          } else {
            this.$message.error('获取空间树失败');
          }
        })
        .catch(error => {
          console.error('获取空间树失败', error);
          this.$message.error('获取空间树失败');
        });
    }
  },
  mounted() {
    if (localStorage.getItem('token') === null) {
      this.$message.error('请先登录！');
      this.$router.push('/login');
    }
    setInterval(() => {
      this.currentTime = new Date().toLocaleString();
    }, 1000);
    this.fetchBaseParams();
    this.fetchWorkspaceTree();
  }
};
</script>

<style scoped>
.dashboard-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #fff;
  color: #333;
  text-align: center;
  line-height: 60px;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12);
}

.header-left {
  font-size: 20px;
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right span {
  margin-right: 20px;
}

.feedback-btn {
  margin-left: 20px;
}

.sidebar {
  background-color: #304156;
  color: #bfcbd9;
  height: 100vh;
  overflow-y: auto;
}

.logo {
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  color: #fff;
  background-color: #2b2f3a;
}

.el-menu {
  border-right: none;
}

.main-content {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
  flex-grow: 1; /* 使主内容区域可扩展填满剩余空间 */
  display: flex;
  flex-direction: column;
}

.fixed-top-nav {
  position: sticky;
  top: 0;
  z-index: 1000;
  background-color: #f0f2f5;
  padding-bottom: 20px;
}

.content-wrapper {
  flex-grow: 1;
  overflow-y: auto;
}

.footer {
  text-align: center;
  padding: 15px 0;
  background-color: #2b2f3a; /* 更好的对比颜色 */
  color: #fff; /* 白色文字 */
}

.footer p {
  margin: 0;
  font-size: 14px;
}

.feedback-dialog {
  border-radius: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}



</style>
